package com.pingtai.user.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.opensymphony.xwork2.ActionContext;
import com.pingtai.dao.AbstractManager;
import com.pingtai.indent.dao.IndentTypeDao;
import com.pingtai.indent.entity.IndentRebateRelation;
import com.pingtai.indent.entity.UserBaseIndentType;
import com.pingtai.indent.entity.UserIndent;
import com.pingtai.indent.entity.UserIndentType;
import com.pingtai.indent.service.WeiboIndentService;
import com.pingtai.security.entity.PubRoles;
import com.pingtai.security.entity.PubUsersRoles;
import com.pingtai.user.dao.PubUsersDao;
import com.pingtai.user.entity.User;
import com.pingtai.user.entity.UserPay;
import com.pingtai.user.entity.UserSearch;
import com.pingtai.util.MyPasswordEncode;
import com.pingtai.util.PaginationSupport;
import com.pingtai.util.Utils;

public class UserManagerService {

	public PubUsersDao userDao;
	public AbstractManager abstractManager;
	private IndentTypeDao indentTypeDao;
	
	public List getAllProduceList(User user,User cUser){
		List cList = new ArrayList();
		if(isRoot(cUser)){
			List baseList = indentTypeDao.findAllBaseIndentType2();
			for(int i=0;i<baseList.size();i++){
				UserBaseIndentType baseIndentType = (UserBaseIndentType) baseList.get(i);
				UserIndentType indentType = new UserIndentType();
				indentType.setUser(user);
				indentType.setUserBaseIndentType(baseIndentType);
				indentType.setUserBaseIndentTypeId(baseIndentType.getId());
				indentType.setPrice(baseIndentType.getPrice());
				cList.add(indentType);
			}
			
		}else{
			cList = indentTypeDao.findUserIndnetType(cUser);
		}
		
		List list = indentTypeDao.findUserIndnetType(user);
		List tmpList = new ArrayList();
		for(int i=0;i<cList.size();i++){
			UserIndentType indentType = (UserIndentType) cList.get(i);
			int baseId = indentType.getUserBaseIndentType().getId();
			if(list==null || list.size()==0){
				indentType.setIsOpen(0);
				tmpList.add(indentType);
				continue;
			}
			boolean flag = false;
			for(int j=0;j<list.size();j++){
				UserIndentType indentType2 = (UserIndentType) list.get(j);
				int baseId2 = indentType2.getUserBaseIndentType().getId();
				if(baseId==baseId2){
					indentType2.setIsOpen(1);
					flag = false;
					break;
				}else{
					flag = true;
				}
			}
			
			if(flag){
				indentType.setIsOpen(0);
				tmpList.add(indentType);
			}
		}
		
		if(list==null){
			list = new ArrayList();
		}
		list.addAll(tmpList);
		list = setBaseIndentTypeHasChild(list);
		return list;
	}
	
	public List setBaseIndentTypeHasChild(List list){
		for(int i=0;i<list.size();i++){
			UserIndentType type = (UserIndentType) list.get(i);
			Set s = type.getUserBaseIndentType().getChildrenBaseIndentType();
			if(s!=null){
				Iterator it = s.iterator();
				while(it.hasNext()){
					type.setHasChild(true);
					break;
				}
			}
		}
		
		return list;
	}
	
	public List findAllBaseIndentType(){
		return indentTypeDao.findAllBaseIndentType();
	}
	
	public List findAllBaseIndentType2(){
		return indentTypeDao.findAllBaseIndentType2();
	}
	
	public List findUserChongzhiList(User user){
		return userDao.findUserChongzhiList(user);
	}
	
	public List findUserKoukuanList(User user){
		return userDao.findUserKoukuanList(user);
	}
	
	public List findUserfanliList(User user){
		return userDao.findUserfanliList(user);
	}

	public IndentTypeDao getIndentTypeDao() {
		return indentTypeDao;
	}

	public void setIndentTypeDao(IndentTypeDao indentTypeDao) {
		this.indentTypeDao = indentTypeDao;
	}

	public AbstractManager getAbstractManager() {
		return abstractManager;
	}

	public void setAbstractManager(AbstractManager abstractManager) {
		this.abstractManager = abstractManager;
	}

	public PubUsersDao getUserDao() {
		return userDao;
	}

	public void setUserDao(PubUsersDao userDao) {
		this.userDao = userDao;
	}

	public void updateUserLoginInfo() {
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		User user = (User) userDao.findUserByname(userName).get(0);
		ActionContext.getContext().getSession().put("userId", user.getUserId());
		Date loginDate = new Date();
		String loginIp = ServletActionContext.getRequest().getRemoteAddr();
		int loginTimes = user.getLoginTimes() == null ? 0 + 1 : user
				.getLoginTimes() + 1;
		
		Date loginDateTmp = user.getThisLoginDate();
		String loginIpTmp = user.getThisLoginIp();
		
		user.setLastLoginTime(loginDateTmp);
		user.setLastLoginIp(loginIpTmp);
		user.setLoginTimes(loginTimes);
		user.setThisLoginDate(loginDate);
		user.setThisLoginIp(loginIp);
		userDao.update(user);
	}
	
	public List findAllChildUsers(){
		User curUser = findCurrectUser();
		return userDao.findAllChildUsers(curUser.getUserId());
	}
	
	public List findAllChildUsers(User user){
		return userDao.findAllChildUsers(user.getUserId());
	}
	
	public PaginationSupport getChildrenUsersForPage_sort(int pageName) {
		Session session = userDao.getSession();
		Integer userId = (Integer) ActionContext.getContext().getSession()
				.get("userId");
		Criteria criteria = session.createCriteria(User.class);

		User user = findCurrectUser();
		if(!isRoot(user)&&!isAdmin(user)){
			criteria = criteria.add(Restrictions.eq("parentUserId", userId));
		}
		if(!isRoot(user)){
			criteria = criteria.add(Restrictions.ne("userAccount", "root"));
		}
		criteria.addOrder(
				Order.desc("money"));
		return abstractManager.findPageByCriteria(criteria, pageName);
	}

	public PaginationSupport getChildrenUsersForPage(int pageName) {
		Session session = userDao.getSession();
		Integer userId = (Integer) ActionContext.getContext().getSession()
				.get("userId");
		Criteria criteria = session.createCriteria(User.class);

		User user = findCurrectUser();
		if(!isRoot(user)&&!isAdmin(user)){
			criteria = criteria.add(Restrictions.eq("parentUserId", userId));
		}
		if(!isRoot(user)){
			criteria = criteria.add(Restrictions.ne("userAccount", "root"));
		}
		criteria.addOrder(
				Order.asc("userId"));
		return abstractManager.findPageByCriteria(criteria, pageName);
	}
	
	public PaginationSupport getChildrenUsersForPage_sort(int pageName, UserSearch qe) {
		Session session = userDao.getSession();
		Integer userId = (Integer) ActionContext.getContext().getSession()
				.get("userId");
		Criteria criteria = session.createCriteria(User.class);
		
		User user = findCurrectUser();
		if(!isRoot(user)&&!isAdmin(user)){
			criteria = criteria.add(Restrictions.eq("parentUserId", userId));
		}
		if(!isRoot(user)){
			criteria = criteria.add(Restrictions.ne("userAccount", "root"));
		}
		
		if (qe != null) {
			if (qe.getAccount() != null && !qe.getAccount().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("userAccount", qe.getAccount()));
			}
			if (qe.getMobile() != null && !qe.getMobile().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("phone", qe.getMobile()));
			}
			if (qe.getQq() != null && !qe.getQq().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("qq", qe.getQq()));
			}
			if (qe.getState() != null) {
				criteria = criteria.add(Restrictions.eq("enabled", qe.getState()));
			}
		}
		criteria = criteria.addOrder(Order.desc("money"));
		return abstractManager.findPageByCriteria(criteria, pageName);
	}

	public PaginationSupport getChildrenUsersForPage(int pageName, UserSearch qe) {
		Session session = userDao.getSession();
		Integer userId = (Integer) ActionContext.getContext().getSession()
				.get("userId");
		Criteria criteria = session.createCriteria(User.class);
		
		User user = findCurrectUser();
		if(!isRoot(user)&&!isAdmin(user)){
			criteria = criteria.add(Restrictions.eq("parentUserId", userId));
		}
		if(!isRoot(user)){
			criteria = criteria.add(Restrictions.ne("userAccount", "root"));
		}
		
		if (qe != null) {
			if (qe.getAccount() != null && !qe.getAccount().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("userAccount", qe.getAccount()));
			}
			if (qe.getMobile() != null && !qe.getMobile().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("phone", qe.getMobile()));
			}
			if (qe.getQq() != null && !qe.getQq().isEmpty()) {
				criteria = criteria.add(Restrictions.eq("qq", qe.getQq()));
			}
			if (qe.getState() != null) {
				criteria = criteria.add(Restrictions.eq("enabled", qe.getState()));
			}
		}
		criteria = criteria.addOrder(Order.asc("userId"));
		return abstractManager.findPageByCriteria(criteria, pageName);
	}

	public UserSearch paseQueryString(UserSearch qe, String queryString) {
		Map param = Utils.URLRequest(queryString);
		if(param.get("qe.account")!=null){
			String account = (String) param.get("qe.account");
			if(!account.isEmpty()){
				qe.setAccount(account);
			}
		}
		
		if(param.get("qe.qq")!=null){
			String qq = (String) param.get("qe.qq");
			if(!qq.isEmpty()){
				qe.setQq(qq);
			}
		}
		
		if(param.get("qe.mobile")!=null){
			String mobile = (String) param.get("qe.mobile");
			if(!mobile.isEmpty()){
				qe.setMobile(mobile);
			}
		}
		
		if(param.get("qe.state")!=null){
			String state = (String) param.get("qe.state");
			if(!state.isEmpty()){
				qe.setState(new Integer(state));
			}
		}
		return qe;
	}

	
	
	
	public boolean checkPassword(String oldPassword){
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		PasswordEncoder encoder = MyPasswordEncode.getEncoder();
		List userList = userDao.findUserByname(userName);
		User user = (User) (userList==null?null:userList.get(0));
		String userPasswordInDB = user==null?null:user.getUserPassword();
		return encoder.matches(oldPassword, userPasswordInDB);
	}
	
	public void updatePassword(String newPassword){
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		PasswordEncoder encoder = MyPasswordEncode.getEncoder();
		List userList = userDao.findUserByname(userName);
		User user = (User) (userList==null?null:userList.get(0));
		String encodeNewPassword = encoder.encode(newPassword);
		user.setUserPassword(encodeNewPassword);
		userDao.update(user);
	}
	
	public void updateEnabled(Integer userId,Integer enabled){
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		List pUserList = userDao.findUserByname(userName);
		User pUser = (User) (pUserList==null?null:pUserList.get(0));
		User user = (User) userDao.getObject(User.class, userId);
		if(isRoot(pUser)|| isAdmin(pUser)){
			user.setEnabled(enabled);
			userDao.update(user);
		}
		
	}
	
	public void updatePassword(Integer userId,String password,boolean self){
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		List pUserList = userDao.findUserByname(userName);
		User pUser = (User) (pUserList==null?null:pUserList.get(0));
		PasswordEncoder encoder = MyPasswordEncode.getEncoder();
		User user = (User) userDao.getObject(User.class, userId);
		
		if(self){
			if(pUser.getUserId()==user.getParentUserId()){
				String encodeNewPassword = encoder.encode(password);
				user.setUserPassword(encodeNewPassword);
				userDao.update(user);
			}
		}else{
			String encodeNewPassword = encoder.encode(password);
			user.setUserPassword(encodeNewPassword);
			userDao.update(user);
		}
		
	}
	
	public User findUserById(int id){
		return (User) userDao.getObject(User.class, id);
	}
	
	public User findCurrectUser(){
		String userName = (String) ActionContext.getContext().getSession()
				.get("userName");
		List userList = userDao.findUserByname(userName);
		return (User) (userList==null?null:userList.get(0));
	}
	
	public void saveUserPay(UserPay userPay){
		userDao.save(userPay);
	}
	
	public int saveUserPay(UserPay userPay , int type){
		try {
			
			User user = findCurrectUser();
			User childUser = (User) userDao.getObject(User.class, userPay.getChildUser().getUserId());
			
			//ROOT用户自己给自己充值扣款
			if(isRoot(user)&&isRoot(childUser)){
				Float userMoney = user.getMoney();
				Float payMoney = userPay.getMoney();
				userMoney += payMoney;
				user.setMoney(userMoney);
//				childUser.setMoney(childUserMoney);
				userPay.setUser(user);
				userPay.setChildUser(childUser);
				userPay.setType(type);
				Date date = new Date();
				userPay.setCreateDate(date);
				userPay.setMoney(Math.abs(userPay.getMoney()));
				userPay.setType2(type);
				userPay.setUserAllMoney(userMoney);
				userDao.save(userPay);
				return 1;
			}
			
			Float payMoney = userPay.getMoney();
			if(type==0){
				userPay.setMoney( payMoney * (-1)) ;
				Float userAllMoney = childUser.getMoney();
				userAllMoney -= userPay.getMoney();
				userPay.setUserAllMoney(userAllMoney);
			}else if (type==1) {
				Float userAllMoney = childUser.getMoney();
				userAllMoney += userPay.getMoney();
				userPay.setUserAllMoney(userAllMoney);
			}
			if(payMoney > user.getMoney()){
				return 0;
			}else{
				Float userMoney = user.getMoney();
				Float childUserMoney = childUser.getMoney();
				userMoney -= payMoney;
				childUserMoney += payMoney;
				user.setMoney(userMoney);
				childUser.setMoney(childUserMoney);
				userPay.setUser(user);
				userPay.setChildUser(childUser);
				userPay.setType(type);
				Date date = new Date();
				userPay.setCreateDate(date);
				userPay.setMoney(Math.abs(userPay.getMoney()));
				userPay.setType2(type);
				userDao.save(userPay);
				UserPay userPay2 = new UserPay();
				userPay2.setChildUser(user);
				userPay2.setUser(childUser);
				userPay2.setCreateDate(date);
				userPay2.setMoney(Math.abs(payMoney));
				userPay2.setUserAllMoney(user.getMoney());
				if(type==0){
					userPay2.setType(1);
				}else if(type==1){
					userPay2.setType(0);
				}
				userDao.save(userPay2);
				return 1;
			}
		} catch (Exception e) {
			return -1;
		}
	}
	
	public List getIndentTypeList(){
		User user = findCurrectUser();
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_ROOT")){
				flag = true;
				break;
			}
		}
		
		if(flag){
			return indentTypeDao.findAllBaseIndentType();
		}else{
			List list = new ArrayList();
			Iterator it2 = user.getUserIndentType().iterator();
			while (it2.hasNext()) {
				UserIndentType type = (UserIndentType) it2.next();
				if(type.getUserBaseIndentType().getParentBaseIndentType()!=null){
					continue;
				}
				list.add(type);
			}
			list = Utils.menuSort(list);
			return list;
		}
		
	}
	
	public boolean isNotUser(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = true;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_USER")){
				flag = false;
				break;
			}
		}
		return flag;
	}
	
	public boolean isUser_2(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_USER_2")){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public boolean isRoot(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_ROOT")){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public boolean isAudit(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_AUDIT")){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public boolean isUser(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_USER")){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public boolean isAdmin(User user){
		Set userRoles =  user.getPubUsersRoleses();
		boolean flag = false;
		Iterator it = userRoles.iterator();
		while (it.hasNext()) {
			PubUsersRoles userRole = (PubUsersRoles) it.next();
			String roleName = userRole.getPubRoles().getRoleName();
			if(roleName.equalsIgnoreCase("ROLE_ADMIN")){
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public List getChildProduceList(User user,UserIndentType indentType){
		return userDao.getChildProduceList(user,indentType);
	}
	
	public List getProduceList2(){
		User curUser = findCurrectUser();
		List produceList = new ArrayList(curUser.getUserIndentType());
		return produceList;
	}
	
	public List getProduceList(User childUser){
		User curUser = findCurrectUser();
		List produceOfChildUser = new ArrayList(childUser.getUserIndentType());
		
		for(int i=0;i<produceOfChildUser.size();i++){
			UserIndentType childUserIndentType = (UserIndentType) produceOfChildUser.get(i);
			childUserIndentType.setIsOpen(1);
		}
		
		List produceOfCur = new ArrayList();
		boolean flag = isRoot(curUser);
		if(flag){
			produceOfCur =  indentTypeDao.findAllBaseIndentType();
		}else{
			produceOfCur = new ArrayList(curUser.getUserIndentType());
		}
		List temp = new ArrayList();
		for(int i=0;i<produceOfCur.size();i++){
			if(flag){
				UserBaseIndentType base = (UserBaseIndentType) produceOfCur.get(i);
				if(produceOfChildUser.size()==0){
					UserIndentType copy = new UserIndentType();
					copy.setPrice(base.getPrice());
					copy.setUser(childUser);
					copy.setUserBaseIndentType(base);
					copy.setIsOpen(0);
					temp.add(copy);
					continue;
				}
				boolean flag2 = false;
				for(int j=0;j<produceOfChildUser.size();j++){
					UserIndentType type = (UserIndentType) produceOfChildUser.get(j);
					if(type.getUserBaseIndentType().getId()==base.getId()){
						flag2 = true;
						break;
					}
				}
				if(!flag2){
					UserIndentType copy = new UserIndentType();
					copy.setPrice(base.getPrice());
					copy.setUser(childUser);
					copy.setUserBaseIndentType(base);
					copy.setIsOpen(0);
					temp.add(copy);
				}
			}else{
				UserIndentType base = (UserIndentType) produceOfCur.get(i);
				if(produceOfChildUser.size()==0){
					UserIndentType copy = new UserIndentType();
					copy.setPrice(base.getPrice());
					copy.setUser(childUser);
					copy.setUserBaseIndentType(base.getUserBaseIndentType());
					copy.setIsOpen(0);
					temp.add(copy);
					continue;
				}
				boolean flag2 = false;
				for(int j=0;j<produceOfChildUser.size();j++){
					UserIndentType type = (UserIndentType) produceOfChildUser.get(j);
					if(type.getUserBaseIndentType().getId()==base.getUserBaseIndentType().getId()) {
						flag2 = true;
						break;
					}
				}
				if(!flag2){
					UserIndentType copy = new UserIndentType();
					copy.setPrice(base.getPrice());
					copy.setUser(childUser);
					copy.setUserBaseIndentType(base.getUserBaseIndentType());
					copy.setIsOpen(0);
					temp.add(copy);
				}
			}
		}
		for(int i=0;i<temp.size();i++){
			produceOfChildUser.add(temp.get(i));
		}
		for(int i=0;i<produceOfChildUser.size();i++){
				UserIndentType type = (UserIndentType) produceOfChildUser.get(i);
				if(type.getUserBaseIndentType().getParentBaseIndentType()!=null){
					produceOfChildUser.remove(i);
					i--;
			}
		}
		return produceOfChildUser;
	}
	
	public boolean isChild(String userid){
		User curUser = findCurrectUser();
		User user = (User) userDao.getObject(User.class, new Integer(userid));
		if(user.getParentUserId()!= curUser.getUserId()){
			return false;
		}
		return true;
	}
	
	public boolean isChildren(User cUser,User user){
		boolean flag = true;
		boolean flag2 = false;
		while(flag){
			if(user.getParentUserId()==cUser.getUserId()){
				flag2 = true;
				break;
			}else{
				if(user.getParentUserId()!=null){
					user = (User) userDao.getObject(User.class, user.getParentUserId());
				}else{
					flag = false;
				}
			}
		}
		return flag2;
	}
	
	public void saveOrUpdateUserProduceType(List userIndentTypes,User user,Map childIndentType,Map childIndentType2){
		User curUser = findCurrectUser();
		List produceOfCur = new ArrayList();
		boolean flag = isRoot(curUser);
		if(flag){
			produceOfCur =  indentTypeDao.findAllBaseIndentType();
		}else{
			produceOfCur = new ArrayList(curUser.getUserIndentType());
		}
		for(int i=0;i<userIndentTypes.size();i++){
			UserIndentType userIndentType = (UserIndentType) userIndentTypes.get(i);
			Integer baseId = null;
			if(userIndentType.getUserBaseIndentType()!=null){
				baseId = userIndentType.getUserBaseIndentType().getId();
			}
			if(baseId==null){
				baseId = userIndentType.getUserBaseIndentTypeId();
			}
			//userIndentType.setId(null);
			if(userIndentType.getIsOpen()==0) {
				userIndentType.setUser(user);
				indentTypeDao.deleteUserIndentType(userIndentType);
				continue;
			}
			
			boolean b = indentTypeDao.getParentUserIndentTypeIsopen(user,baseId);
			if(!b) continue;
			
			userIndentType.setUser(user);
			
			for(int j=0;j<produceOfCur.size();j++){
				if(flag){
					UserBaseIndentType base = (UserBaseIndentType) produceOfCur.get(j);
					if(base.getId()!=baseId) continue;
					if(userIndentType.getPrice()!=null) {
						if(base.getPrice()>userIndentType.getPrice()){
							userIndentType.setPrice(base.getPrice());
						}
					}
					break;
				}else{
					UserIndentType base = (UserIndentType) produceOfCur.get(j);
					if(base.getUserBaseIndentType().getId()!=baseId) continue;
					if(userIndentType.getPrice()!=null) {
						if(base.getPrice()>userIndentType.getPrice()){
							userIndentType.setPrice(base.getPrice());
						}
					}
					break;
				}
			}
			
			List l = indentTypeDao.findUserIndentType(user,baseId);
			
			if(l!=null&&l.size()>0){
				UserIndentType tmp = (UserIndentType) l.get(0);
				tmp.setPrice(userIndentType.getPrice());
				UserBaseIndentType base = tmp.getUserBaseIndentType().getParentBaseIndentType();
				if(base!=null){
					List li = indentTypeDao.findUserIndentType(user, base.getId());
					if(li!=null&&li.size()>0){
						UserIndentType ty = (UserIndentType) li.get(0);
						tmp.setParentIndentType(ty);
					}
				}
				UserBaseIndentType base2 = tmp.getUserBaseIndentType();
				tmp.setBasePrice(base2.getPrice());
				tmp.setUpdateDate(base2.getUpdateDate());
				indentTypeDao.saveUserIndentType(tmp);
			}else{
					UserBaseIndentType base = (UserBaseIndentType) indentTypeDao.getObject(UserBaseIndentType.class, baseId);
					UserBaseIndentType parentBase = base.getParentBaseIndentType();
					userIndentType.setUserBaseIndentType(base);
					if(parentBase!=null){
						List li = indentTypeDao.findUserIndentType(user, parentBase.getId());
						if(li!=null&&li.size()>0){
							UserIndentType ty = (UserIndentType) li.get(0);
							userIndentType.setParentIndentType(ty);
						}
					}
					UserBaseIndentType base2 = userIndentType.getUserBaseIndentType();
					userIndentType.setBasePrice(base2.getPrice());
					userIndentType.setUpdateDate(base2.getUpdateDate());
				    indentTypeDao.save(userIndentType);
			}
			
			
		}
	}
	
	public void updateUserIndentTypeDefaultPrice(List list){
		for(int i=0;i<list.size();i++){
			UserIndentType indentType = (UserIndentType) list.get(i);
			if(indentType!=null&&indentType.getDefaultPrice()!=null){
				UserIndentType indentTypeDb = (UserIndentType) indentTypeDao.getObject(UserIndentType.class, indentType.getId());
				indentTypeDb.setDefaultPrice(indentType.getDefaultPrice());
				indentTypeDao.saveUserIndentType(indentTypeDb);
			}
		}
	}
	
	public void saveOrUpdateUserProduceType2(List produceOfCur,boolean flag,User curUser,List userIndentTypes,User user,Map childIndentType,Map childIndentType2){
		for(int i=0;i<userIndentTypes.size();i++){
			UserIndentType userIndentType = (UserIndentType) userIndentTypes.get(i);
			Integer baseId = null;
			if(userIndentType.getUserBaseIndentType()!=null){
				baseId = userIndentType.getUserBaseIndentType().getId();
			}
			if(baseId==null){
				baseId = userIndentType.getUserBaseIndentTypeId();
			}
			if(userIndentType.getIsOpen()==0) {
				continue;
			}
			
			boolean b = indentTypeDao.getParentUserIndentTypeIsopen(user,baseId);
			if(!b) continue;
			userIndentType.setUser(user);
			
			for(int j=0;j<produceOfCur.size();j++){
				if(flag){
					UserBaseIndentType base = (UserBaseIndentType) produceOfCur.get(j);
					if(base.getId()!=baseId) continue;
					if(userIndentType.getPrice()!=null) {
						if(base.getPrice()>userIndentType.getPrice()){
							userIndentType.setPrice(base.getPrice());
						}
					}
					break;
				}else{
					UserIndentType base = (UserIndentType) produceOfCur.get(j);
					if(base.getUserBaseIndentType().getId()!=baseId) continue;
					if(userIndentType.getPrice()!=null) {
						if(base.getPrice()>userIndentType.getPrice()){
							userIndentType.setPrice(base.getPrice());
						}
					}
					break;
				}
			}
			
			List l = indentTypeDao.findUserIndentType(user,baseId);
			
			if(l!=null&&l.size()>0){
				UserIndentType tmp = (UserIndentType) l.get(0);
				tmp.setPrice(userIndentType.getPrice());
				UserBaseIndentType base = tmp.getUserBaseIndentType().getParentBaseIndentType();
				if(base!=null){
					List li = indentTypeDao.findUserIndentType(user, base.getId());
					if(li!=null&&li.size()>0){
						UserIndentType ty = (UserIndentType) li.get(0);
						tmp.setParentIndentType(ty);
					}
				}
				UserBaseIndentType base2 = tmp.getUserBaseIndentType();
				tmp.setBasePrice(base2.getPrice());
				tmp.setUpdateDate(base2.getUpdateDate());
				indentTypeDao.saveUserIndentType(tmp);
			}else{
					UserBaseIndentType base = (UserBaseIndentType) indentTypeDao.getObject(UserBaseIndentType.class, baseId);
					UserBaseIndentType parentBase = base.getParentBaseIndentType();
					userIndentType.setUserBaseIndentType(base);
					if(parentBase!=null){
						List li = indentTypeDao.findUserIndentType(user, parentBase.getId());
						if(li!=null&&li.size()>0){
							UserIndentType ty = (UserIndentType) li.get(0);
							userIndentType.setParentIndentType(ty);
						}
					}
					UserBaseIndentType base2 = userIndentType.getUserBaseIndentType();
					userIndentType.setBasePrice(base2.getPrice());
					userIndentType.setUpdateDate(base2.getUpdateDate());
				    indentTypeDao.save(userIndentType);
			}
			
			userIndentType = null;
		}
		
		}
	
	
//	public void saveOrUpdateUserProduceType(List userIndentTypes,User user,Map childIndentType,Map childIndentType2){
//		User curUser = findCurrectUser();
//		List produceOfCur = new ArrayList();
//		boolean flag = isRoot(curUser);
//		if(flag){
//			produceOfCur =  indentTypeDao.findAllBaseIndentType();
//		}else{
//			produceOfCur = new ArrayList(curUser.getUserIndentType());
//		}
//		for(int i=0;i<userIndentTypes.size();i++){
//			UserIndentType userIndentType = (UserIndentType) userIndentTypes.get(i);
//			Integer baseId = null;
//			if(userIndentType.getUserBaseIndentType()!=null){
//				baseId = userIndentType.getUserBaseIndentType().getId();
//			}
//			if(baseId==null){
//				baseId = userIndentType.getUserBaseIndentTypeId();
//			}
//			//userIndentType.setId(null);
//			if(userIndentType.getIsOpen()==0) {
//				userIndentType.setUser(user);
//				indentTypeDao.deleteUserIndentType(userIndentType);
//				continue;
//			}
//			userIndentType.setUser(user);
//			
//			for(int j=0;j<produceOfCur.size();j++){
//				if(flag){
//					UserBaseIndentType base = (UserBaseIndentType) produceOfCur.get(j);
//					if(base.getId()!=baseId) continue;
//					if(userIndentType.getPrice()!=null) {
//						if(base.getPrice()>userIndentType.getPrice()){
//							userIndentType.setPrice(base.getPrice());
//						}
//					}
//				}else{
//					UserIndentType base = (UserIndentType) produceOfCur.get(j);
//					if(base.getUserBaseIndentType().getId()!=baseId) continue;
//					if(userIndentType.getPrice()!=null) {
//						if(base.getPrice()>userIndentType.getPrice()){
//							userIndentType.setPrice(base.getPrice());
//						}
//					}
//				}
//			}
//			
//			List l = indentTypeDao.findUserIndentType(user,baseId);
//			
//			if(l!=null&&l.size()>0){
//				UserIndentType tmp = (UserIndentType) l.get(0);
//				tmp.setPrice(userIndentType.getPrice());
//				indentTypeDao.saveUserIndentType(tmp);
//			}else{
//				
//					UserBaseIndentType base = (UserBaseIndentType) indentTypeDao.getObject(UserBaseIndentType.class, baseId);
//					userIndentType.setUserBaseIndentType(base);
//				
//				indentTypeDao.saveUserIndentType(userIndentType);
//			}
//			
//			l = indentTypeDao.findUserIndentType(user,baseId);
//			if(l!=null&&l.size()>0){
//				UserIndentType tmp = (UserIndentType) l.get(0);
//				UserBaseIndentType base = (UserBaseIndentType) indentTypeDao.getObject(UserBaseIndentType.class, baseId);
//				Set childBaseIndentType= base.getChildrenBaseIndentType();
//				
//				if(childBaseIndentType==null) continue;
//				Iterator it = childBaseIndentType.iterator();
//				while(it.hasNext()){
//					UserBaseIndentType b = (UserBaseIndentType) it.next();
//					
//					String key = base.getBaseIndentTypeClassify().getName2()+base.getName2()+b.getName2();
//					String price = (String) childIndentType.get(key);
//					String baseId2 = (String) childIndentType2.get(key);
//					List l2 = indentTypeDao.findUserIndentType2(user, new Integer(baseId2));
//					if(l2!=null&&l2.size()>0){
//						UserIndentType c = (UserIndentType) l2.get(0);
//						if(c.getUserBaseIndentType().getPrice()>new Float(price)){
//							continue;
//						}
//						c.setIsOpen(1);
//						c.setParentIndentType(tmp);
//						c.setPrice(new Float(price));
//						c.setUser(user);
//						c.setUserBaseIndentType(b);
//						indentTypeDao.saveUserIndentType(c);
//					}else{
//						UserIndentType c = new UserIndentType();
//						UserBaseIndentType b2 = (UserBaseIndentType) indentTypeDao.getObject(UserBaseIndentType.class, new Integer(baseId2));
//						if(b2.getPrice()> new Float(price)){
//							continue;
//						}
//						c.setIsOpen(1);
//						c.setParentIndentType(tmp);
//						c.setPrice(new Float(price));
//						c.setUser(user);
//						c.setUserBaseIndentType(b2);
//						indentTypeDao.saveUserIndentType(c);
//					}
//					
//				}
//				
//			}
//		}
//	}
	
	public int addUser(User user,int type){
		User curUser = findCurrectUser();
		if(userDao.findUserByname(user.getUserAccount()).size()>0){
			return -1;  //有相同账户
		}
		
		User u = new User();
		
		u.setUserAccount(user.getUserAccount());
		u.setParentUserId(curUser.getUserId());
		u.setEnabled(1);
		u.setUserName(user.getUserAccount());
		u.setMoney(0.0f);
		u.setRegisterTime(new Date());
		String pass = user.getUserPassword();
		pass = MyPasswordEncode.getEncoder().encode(pass);
		u.setUserPassword(pass);
		PubUsersRoles userRole = new PubUsersRoles();
		userRole.setEnabled(1);
		userRole.setPubUsers(u);
		PubRoles role = null;
		if(isRoot(curUser)){
			if(type==0){
				role = userDao.findRoleByRoleName("ROLE_ADMIN");
			}else if(type==1){
				role = userDao.findRoleByRoleName("ROLE_AUDIT");
			}
			
		}else {
			if(isAdmin(curUser)){
				role = userDao.findRoleByRoleName("ROLE_USER");
			}else if(isUser(curUser)){
				role = userDao.findRoleByRoleName("ROLE_USER_2");
			}else if(isUser_2(curUser)){
				return 403;
			}
		}
		userRole.setPubRoles(role);
		Set s = new HashSet();
		s.add(userRole);
		user.setPubUsersRoleses(s);
		
		String parentUserString = ":";
		Integer parentId = u.getParentUserId();
		parentUserString += parentId +":";
		User parent = null;
		while(true){
			parent = (User) userDao.getObject(User.class, parentId);
			parentId = parent.getParentUserId();
			if(parentId!=null){
				parentUserString += parentId +":";
				parent = (User) userDao.getObject(User.class, parentId);
			}else{
				break;
			}
		}
		
		u.setParentUserIdString(parentUserString);
		u = (User) userDao.save(u);
		parentUserString = ":"+u.getUserId()+parentUserString;
		u.setParentUserIdString(parentUserString);
//		if(role.getRoleName().equals("ROLE_AUDIT")){
//			parentUserString = ":" + curUser.getUserId() + ":";
//			u.setParentUserIdString(parentUserString);
//		}
		userDao.update(u);
		userDao.save(userRole);
		return 1;  //保存成功
	}
	
	public User findUserByName(String name){
		List l = userDao.findUserByname(name);
		if(l!=null&&l.size()>0){
			return (User) l.get(0);
		}
		return null;
	}
	/**
	 * 
	 * @param user
	 * @param tpye 0 生成订单扣款  1 订单退款
	 */
	public UserPay saveUserMoneyForIndent(User user,int type,Float money,UserIndent userIndent){
		userDao.update(user);
		UserPay userPay = new UserPay();
		userPay.setCreateDate(new Date());
		userPay.setMoney(money);
		userPay.setType(type);
		userPay.setUserAllMoney(user.getMoney());
		userPay.setChildUser(user);
		userPay.setUserIndent(userIndent);
		userPay.setUserBaseIndent(userIndent.getBaseIndentType());
		userPay.setIndentCreateUser(userIndent.getUser());
		userPay = (UserPay) userDao.save(userPay);
		return userPay;
	}
	
	public void saveOrUpdateUser(User user){
		userDao.saveOrUpdate(user);
	}
	
	public void userIndentRebate(UserIndent userIndent){
		List rebateList = userDao.findRebateRelation(userIndent);
		for(int i=0;i<rebateList.size();i++){
			IndentRebateRelation indentRebateRelation = (IndentRebateRelation) rebateList.get(i);
			User user = indentRebateRelation.getUser();
			Float rebateMoney = indentRebateRelation.getRebateMoney();
			if(rebateMoney>0){
				user.setMoney(user.getMoney()+rebateMoney);
				UserPay userPay = new UserPay();
				userPay.setChildUser(user);
				userPay.setCreateDate(new Date());
				userPay.setMoney(rebateMoney);
				userPay.setType(1);
				userPay.setUserAllMoney(user.getMoney());
				userPay.setIndentCreateUser(userIndent.getUser());
				User rootUser = findUserById(1);
				userPay.setUser(rootUser);
				userPay.setUserIndent(userIndent);
				userPay.setUserBaseIndent(userIndent.getBaseIndentType());
				userPay.setIndentCreateUser(userIndent.getUser());
				userDao.saveOrUpdate(user);
				saveUserPay(userPay);
			}
		}
	}
	
	public Float getAllChildrensMoney(User user,Float money){
//		List userList = findAllChildUsers(user);
//		
//		for(int i=0;i<userList.size();i++){
//			User cUser = (User) userList.get(i);
//			money += cUser.getMoney();
//			money = getAllChildrensMoney(cUser, money);
//		}
		money = money + userDao.findAllChildUsersMoney(user.getUserId()).floatValue();
		if(!isUser_2(user)) money -= user.getMoney();
		return money;
	}
	
	public Map getIndentTypeMap(List typeList){
		Map map = new LinkedHashMap();
		for(int i=0;i<typeList.size();i++){
			Object baseIndentType =  typeList.get(i);
			
			if(baseIndentType instanceof UserBaseIndentType){
				UserBaseIndentType o  = (UserBaseIndentType)baseIndentType;
				String classifyName = o.getBaseIndentTypeClassify().getName();
				List obj = (List) map.get(classifyName);
				if(obj==null){
					obj = new ArrayList();
					obj.add(o);
					map.put(classifyName, obj);
				}else{
					obj.add(o);
					map.put(classifyName, obj);
				}
			}else if(baseIndentType instanceof UserIndentType){
				UserBaseIndentType obj  = ((UserIndentType)baseIndentType).getUserBaseIndentType();
				String classifyName = obj.getBaseIndentTypeClassify().getName();
				List list = (List) map.get(classifyName);
				if(list==null){
					list = new ArrayList();
					list.add(obj);
					map.put(classifyName, list);
				}else{
					list.add(obj);
					map.put(classifyName, list);
				}
			}
		}
		return map;
	}
}
